<template>
  <div v-loading="loading" class="order-detail-page">
    <el-page-header @back="goBack">
      <template #content>
        <span class="page-title">订单详情</span>
      </template>
    </el-page-header>

    <el-card class="order-info-card">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
          <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ order.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ order.username || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(order.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">
          <span class="amount">¥{{ order.totalAmount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodText(order.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ formatDate(order.payTime) || '未支付' }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ formatDate(order.shipTime) || '未发货' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ formatDate(order.completeTime) || '未完成' }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ order.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话" :span="2">{{ order.phone || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="order-items-card">
      <template #header>
        <div class="card-header">商品清单</div>
      </template>

      <el-table :data="order.items" border stripe>
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              :src="getImageUrl(row.productImage)"
              fit="cover"
              style="width: 60px; height: 60px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">¥{{ row.price }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" align="center" />
        <el-table-column prop="subtotal" label="小计" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.subtotal }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="order-total">
        <span>订单总额：</span>
        <span class="total-amount">¥{{ order.totalAmount }}</span>
      </div>
    </el-card>

    <div class="order-actions">
      <el-button v-if="order.status === 'paid'" type="warning" @click="handleShip">
        发货
      </el-button>
      <el-button v-if="order.status === 'shipped'" type="success" @click="handleComplete">
        完成订单
      </el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAdminOrderDetail, shipOrder, completeOrder } from '@/api/order'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const order = ref({
  items: []
})

onMounted(() => {
  loadOrderDetail()
})

const loadOrderDetail = async () => {
  loading.value = true
  try {
    const res = await getAdminOrderDetail(route.params.id)
    if (res.code === 200 && res.data) {
      order.value = res.data
    } else {
      ElMessage.error(res.message || '加载订单详情失败')
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error('加载订单详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const handleShip = async () => {
  try {
    const res = await shipOrder(order.value.id)
    if (res.code === 200) {
      ElMessage.success('订单已发货')
      loadOrderDetail()
    } else {
      ElMessage.error(res.message || '发货失败')
    }
  } catch (error) {
    console.error('发货失败', error)
    ElMessage.error('发货失败')
  }
}

const handleComplete = async () => {
  try {
    const res = await completeOrder(order.value.id)
    if (res.code === 200) {
      ElMessage.success('订单已完成')
      loadOrderDetail()
    } else {
      ElMessage.error(res.message || '完成订单失败')
    }
  } catch (error) {
    console.error('完成订单失败', error)
    ElMessage.error('完成订单失败')
  }
}

const getImageUrl = (image) => {
  if (!image) return 'https://via.placeholder.com/60'
  if (image.startsWith('http://') || image.startsWith('https://')) return image
  // 处理相对路径，移除开头的斜杠避免双斜杠
  const path = image.startsWith('/') ? image.slice(1) : image
  return `http://localhost:8080/${path}`
}

const getStatusType = (status) => {
  const typeMap = {
    unpaid: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    unpaid: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return textMap[status] || status
}

const getPaymentMethodText = (method) => {
  const methodMap = {
    cash: '现金',
    alipay: '支付宝',
    wechat: '微信支付'
  }
  return methodMap[method] || method
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped lang="scss">
.order-detail-page {
  padding: 20px;

  .page-title {
    font-size: 20px;
    font-weight: bold;
  }

  .el-page-header {
    margin-bottom: 20px;
  }

  .order-info-card,
  .order-items-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: bold;
    }

    .amount {
      color: #f56c6c;
      font-weight: bold;
      font-size: 16px;
    }
  }

  .order-total {
    margin-top: 20px;
    text-align: right;
    font-size: 18px;
    font-weight: bold;

    .total-amount {
      color: #f56c6c;
      font-size: 24px;
      margin-left: 10px;
    }
  }

  .order-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>




